package cs419.magnusmi.trackitcs;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Mikael Magnuson on 2/6/14.
 */

public class Inventory extends ActionBarActivity {
    ListView listView;
    Button add;
    ItemGetList iGetList;
    Context k;
    String user;
    String API;
    public String barData;
    Button basicSearch;
    Button advSearch;
    EditText searchBox;
    String newId;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.inventory_view);

        //define listview for inventory
        listView = (ListView) findViewById(R.id.listView);


        //capture context of activity for use in asynchronous activity
        k = this;

        //create new async array list to hold item information and execute get task
        iGetList = new ItemGetList();
        iGetList.execute((Void) null);

        Intent i = getIntent();
        user = i.getStringExtra("user");
        API = i.getStringExtra("API");

        //search process
        basicSearch = (Button) findViewById(R.id.search_Button);
        searchBox = (EditText) findViewById(R.id.search_Field);

        basicSearch.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                //Launching add activity
                validate();
            }
        });

        advSearch = (Button) findViewById(R.id.advSearchButton);
        advSearch.setOnClickListener(new View.OnClickListener(){

            public void onClick(View view){
                Intent i = new Intent(getApplicationContext(), AdvSearch.class);
                Utility.addToIntent(i, user, API);
                startActivity(i);
            }
        });

        //Pulls up the ZXing barcode scanner on the phone to add new item
        try {
            Button scanner = (Button)findViewById(R.id.add_Button);
            scanner.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    //Starts the Code Reader
                    Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                    intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
                    startActivityForResult(intent, 0);

                }

            });

        } catch (ActivityNotFoundException anfe) {
            Log.e("onCreate", "Scanner Not Found", anfe);
        }

        //Pulls up the ZXing barcode scanner on the phone to search by barcode
        try {
            Button scanner = (Button)findViewById(R.id.scan_Button);
            scanner.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    //Starts the Code Reader
                    Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                    intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
                    startActivityForResult(intent, 1);
                }

            });

        } catch (ActivityNotFoundException anfe) {
            Log.e("onCreate", "Scanner Not Found", anfe);
        }

    }

    //Handle variables captured from the ZXing barcode scanner
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 0 || requestCode == 1) {
            if (resultCode == RESULT_OK) {
                String contents = intent.getStringExtra("SCAN_RESULT");
                String format = intent.getStringExtra("SCAN_RESULT_FORMAT");

                barData = intent.getStringExtra("SCAN_RESULT");

                //just displays on screen what was scanned
                Toast toast = Toast.makeText(this, "Content:" + contents + " Format:" + format , Toast.LENGTH_LONG);
                toast.setGravity(Gravity.TOP, 25, 400); //here it is (context, text, duration)
                toast.show();

                newId = barData;

                boolean cancel = false;
                View focusView = null;

                //confirm input is not empty
                if (TextUtils.isEmpty(newId)){
                    cancel = true;
                    Context context = getApplicationContext();
                    CharSequence text = "There was no scan recorded. Scan was NULL";
                    int duration = Toast.LENGTH_SHORT;

                    Toast errToast = Toast.makeText(context, text, duration);
                    errToast.show();
                }

                //if not empty, confirm input is an integer
                else {
                    try {
                        Integer.parseInt(newId);
                    }
                    catch (NumberFormatException e){
                        cancel = true;
                        Context context = getApplicationContext();
                        CharSequence text = "The scanned barcode must represent only a number. Number exception.";
                        int duration = Toast.LENGTH_SHORT;

                        Toast errToast = Toast.makeText(context, text, duration);
                        errToast.show();
                    }
                }

                if(!cancel){
                    if(requestCode == 0) {
                        Intent i = new Intent(getApplicationContext(), addDetail.class);
                        i.putExtra("newItemID", newId);
                        Utility.addToIntent(i, user, API);
                        startActivity(i);
                    }
                    else if(requestCode == 1) {
                        Intent i = new Intent(getApplicationContext(), ItemView.class);
                        i.putExtra("id", newId);
                        Utility.addToIntent(i, user, API);
                        startActivity(i);
                    }
                }

            } else if (resultCode == RESULT_CANCELED) {
                // Handle cancel
                Toast toast = Toast.makeText(this, "Scan was Cancelled!", Toast.LENGTH_LONG);
                toast.setGravity(Gravity.TOP, 25, 400); //here it is (context, text, duration)
                toast.show();
            }
        }
    }

    public void validate() {

        searchBox.setError(null);

        String query = searchBox.getText().toString();

        boolean cancel = false;
        View focusView = null;


        // Check for a search query
        if (TextUtils.isEmpty(query)) {
            searchBox.setError(getString(R.string.error_field_required));
            cancel = true;
            focusView = searchBox;
        }

        if (cancel) {
            // There was an error; don't attempt search and focus the first
            // form field with an error.
            focusView.requestFocus();
        }

        else{

            Intent i = new Intent(getApplicationContext(), BasicSearch.class);
            Utility.addToIntent(i, user, API);
            i.putExtra("query", query);
            startActivity(i);

        }
    }

    @Override
    public boolean onCreateOptionsMenu (Menu menu)  {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.logout:
                Intent i = new Intent(getApplicationContext(), MainActivity.class);
                //clear stack to enforce logout (http://stackoverflow.com/questions/3007998/on-logout-clear-activity-history-stack-preventing-back-button-from-opening-l)
                i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                        Intent.FLAG_ACTIVITY_CLEAR_TASK |
                        Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
                return true;
            case R.id.inventory_menu:
                Intent j = new Intent(getApplicationContext(), Inventory.class);
                Utility.addToIntent(j, user, API);
                startActivity(j);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * Represents an asynchronous login/registration task used to get item list
     * the user.
     */

    public class ItemGetList extends AsyncTask<Void, Void, JSONObject> {

        //array list to store item descriptor strings
        ArrayList<String> items  = new ArrayList<String>();
        //array list to store item IDs (parallels items list; for passing to itemView intents)
        ArrayList<Integer> itemIDs = new ArrayList<Integer>();

        /**
         * Gets inventory from database
         * @param params none
         * @return json object containing database inventory results
         */
        @Override
        protected JSONObject doInBackground(Void... params) {

            //DEBUG System.out.println("Inventory started");

            //url of PHP to get list
            String getList = "http://web.engr.oregonstate.edu/~cohenad/cs419/index.php/InventoryList";

            //pointer to array list on inventory page

            //execute get request for list
            JSONParser jsonParser = new JSONParser();
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("null", "null"));

            JSONObject json = jsonParser.makeHttpRequest(getList, "GET", parameters);
            //DEBUG out.println("Inventory done");
            return json;
        }

        /**
         * Method to add content to listview after getting content online
         * @param json json array containing results of HTTP get
         */
        @Override
        protected void onPostExecute(JSONObject json) {


            //parse JSON array
            try{
                //create list of items to print.  these are saved in json array with identifier "display[index]"
                int length = json.getInt("Length");
                for (int i = 0; i < length; i++){
                    items.add(json.getString("display" + i));
                }
                //create array of ids to match items for use in clicking links.  These are saved in json array with identifier "id[index]"
                for (int i = 0; i < length; i++){
                    itemIDs.add(json.getInt("id" + i));
                }
                //DEBUG System.out.println("Inventory done 2");
            }
            catch (JSONException e) {
                Log.d("JSONErr", "JSON error");
            }

            // Define a new Adapter
            // First parameter - Context
            // Second parameter - Layout for the row
            // Third parameter - ID of the TextView to which the data is written
            // Fourth - the Array of data (returned from async task)
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(k,
                    android.R.layout.simple_list_item_1, android.R.id.text1, items){
                @Override
                public View getView(int position, View convertView,
                                    ViewGroup parent) {
                    View view =super.getView(position, convertView, parent);

                    TextView textView=(TextView) view.findViewById(android.R.id.text1);

                    /*YOUR CHOICE OF COLOR*/
                    textView.setTextColor(Color.WHITE);

                    return view;
                }
            };

            // Assign adapter to ListView
            listView.setAdapter(adapter);

            // Create click listener for each item
            AdapterView.OnItemClickListener detailListen = new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View v, int position, long ident) {
                    //DEBUG System.out.println("Id is:" + itemIDs.get(position));

                    //on click, bring up item detail view
                    Intent display = new Intent(getApplicationContext(), ItemView.class);
                    String id = itemIDs.get(position).toString();
                    display.putExtra("id", id);
                    Utility.addToIntent(display, user, API);
                    startActivity(display);
                }
            };
            //assign item listener to listview
            listView.setOnItemClickListener(detailListen);
        }
    }
}
